package com.yiyiooo.Abp;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


import androidx.fragment.app.FragmentManager;

import com.yiyiooo.Abp.basics.AbpApiCallback;
import com.yiyiooo.Abp.basics.AbpInterceptors;
import com.yiyiooo.Abp.basics.AbpLog;
import com.yiyiooo.Abp.basics.AbpResultDto;
import com.yiyiooo.Abp.basics.AbpSession;
import com.yiyiooo.Abp.basics.AppMessage;
import com.yiyiooo.Abp.basics.HttpClientResult;
import com.yiyiooo.Abp.basics.LocalStore;
import com.yiyiooo.client.api.TokenAuthApi;
import com.yiyiooo.client.invoker.ApiException;
import com.yiyiooo.client.invoker.Configuration;
import com.yiyiooo.client.model.AuthenticateModel;
import com.yiyiooo.client.model.AuthenticateResultModel;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;

import org.threeten.bp.LocalDateTime;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.format.DateTimeFormatter;

import java.io.IOException;
import java.util.Locale;
import java.util.Objects;

public class AppBootstrap extends Application{
    private static Context appContext;
    @SuppressLint("HandlerLeak")
    public static Handler handler = new Handler(){};
    public static FragmentManager manager;
    public static LocalStore localStore;
    @Override
    public void onCreate() {
        super.onCreate();
        appContext = getApplicationContext();
        localStore = LocalStore.getInstance();
        init();
    }

    static public Context getAppContext(){
        return appContext;
    }

    static public void init(){
        AppMessage.Debug("AppBootstrap init");
        Configuration.getDefaultApiClient().setBasePath(AppConst.remoteServiceBaseUrl);
        AbpInterceptors abpInterceptors = new AbpInterceptors();
        abpInterceptors.apiErrorHandel = new AbpInterceptors.ApiErrorHandel() {
            public void handel401() {
                try{
                    if(AbpSession.getInstance().getPassword()!=null&&!Objects.equals(AbpSession.getInstance().getPassword(),"")){
                        AbpSession.getInstance().logout();
                        AuthenticateModel model = new AuthenticateModel();
                        model.setPassword(AbpSession.getInstance().getPassword());
                        model.setUserNameOrEmailAddress(AbpSession.getInstance().getUser().getUserName());
                        try {
                            new TokenAuthApi().apiTokenAuthAuthenticatePostAsync(model,new AbpApiCallback<AuthenticateResultModel>(){
                                @Override
                                public void call(HttpClientResult<AuthenticateResultModel> callData) {
                                    if(callData.error) return;
                                    AbpSession.getInstance().login(callData.result);
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            AppMessage.Success("登录成功");
                                        }
                                    });
                                }
                            });
                        }catch (ApiException ex){
                            AppMessage.Err("登录失败"+ex.getMessage());
                        }
                        return;
                    }
                    if(AbpSession.getInstance().getAccessToken()==null||AbpSession.getInstance().getAccessToken().equals(""))
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getAppContext(), "没有登录，请登录", Toast.LENGTH_SHORT).show();
                            }
                        });
                    else
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getAppContext(), "登录过期，请重新登录", Toast.LENGTH_SHORT).show();
                            }
                        });
                    // 弹窗登录窗口
                    // handler.post(new Runnable() {
                    //     @Override
                    //     public void run() {
                    //         LoginFragment.showDialog();
                    //     }
                    // });
                }catch (Exception e){
                    Log.e("AbpInterceptors",""+e.getMessage());
                }
            }

            @Override
            public void handelError(Response response) {
                try {
                    ResponseBody responseBody = response.body();
                    if(response.code()==401) handel401();
                    if(responseBody!=null&&responseBody.contentLength()>0){
                        String responseBodyString = responseBody.string();
                        final AbpResultDto result = new JSON().deserialize(responseBodyString,AbpResultDto.class);
                        if(!result.success&&result.error!=null){
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    AbpLog.e("AbpInterceptors","url: "+response.request().urlString()+" :\nmessage: "+result.error.message+"\n"+"detail: "+result.error.details);
                                }
                            });
                        }else {
                            AbpLog.e("AbpInterceptors","RequestError: "+response.request().urlString() +" "+ response.message());
                        }
                    }else {
                        AbpLog.e("AbpInterceptors","RequestError: "+response.request().urlString() +" "+ response.message());
                    }
                }catch (IOException ex){
                    AbpLog.e("AbpInterceptors", ex.getMessage());
                }
            }

            @Override
            public void handelSuccess(Response response) {
                Log.i("AbpInterceptors", response.request().method()+" success "+response.request().urlString());
            }
        };
        Configuration.getDefaultApiClient().getHttpClient().interceptors().add(abpInterceptors);
        AbpSession.getInstance();
        try {
            String t = "2021-01-02 12:06:06";
//            TimeZone utcZone = TimeZone.getTimeZone("UTC");
//            Date d = GlobalOption.simpleDateFormat.parse(t);
            LocalDateTime localDateTime = LocalDateTime.parse(t,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss",Locale.CHINA));
            OffsetDateTime dtNow = OffsetDateTime.now();
            AppMessage.Debug(dtNow.toString(),"1");
            AppMessage.Debug(dtNow.toLocalDateTime().format(DateTimeFormatter.ISO_DATE_TIME),"2");
            AppMessage.Debug(dtNow.toLocalDateTime().toString(),"3");
            AppMessage.Debug(OffsetDateTime.of(localDateTime,ZoneOffset.ofHours(8)).toString(),"4");
            AppMessage.Debug(OffsetDateTime.of(LocalDateTime.parse(t,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss",Locale.CHINA)),ZoneOffset.UTC).toString(),"5");
        }catch (Exception e){
            AppMessage.Err(e.getMessage());
        }
    }
}
